package sun.springboot.mqtt_integration.core.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;

/**
 * mqtt服务注册
 */
@Configuration
public class InboundConfig {

    private MqttPropertiesConfig mqttPropertiesConfig;

    public InboundConfig(MqttPropertiesConfig mqttPropertiesConfig) {
        this.mqttPropertiesConfig = mqttPropertiesConfig;
    }

    /*mqtt配置工厂*/
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory defaultMqttPahoClientFactory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(mqttPropertiesConfig.getUserName());
        mqttConnectOptions.setPassword(mqttPropertiesConfig.getPassword().toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{mqttPropertiesConfig.getServer()});
        defaultMqttPahoClientFactory.setConnectionOptions(mqttConnectOptions);
        return defaultMqttPahoClientFactory;
    }

    /*消息监听渠道--入站*/
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    /*消息监听渠道--出站*/
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /*消息监听配置*/
    @Bean
    public MessageProducer inbound() {
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(mqttPropertiesConfig.getSubscribeClientId(), mqttClientFactory(), mqttPropertiesConfig.getTopics().split(","));
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    /*消息出站配置*/
    @Bean
    public MqttPahoMessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler =
                new MqttPahoMessageHandler(mqttPropertiesConfig.getProviderClientId(), mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setCompletionTimeout(5000);
        return messageHandler;
    }


}
